package panda.query.tree.index;

import panda.index.Index;
import panda.metainfo.IndexToken;
import panda.query.scan.Scanner;
import panda.query.scan.TableScanner;
import panda.query.scan.index.IndexJoinScanner;
import panda.query.struct.Attribute;
import panda.query.tree.QueryTreeNode;
import panda.record.Schema;
import panda.transaction.Transaction;

public class IndexJoinNode implements QueryTreeNode{
	private QueryTreeNode l, r;
	private IndexToken it;
	private Attribute join;
	private Schema sch = new Schema();
	
	public IndexJoinNode(QueryTreeNode l, QueryTreeNode r, IndexToken it, Attribute join, Transaction tx) {
		this.l = l;
		this.r = r;
		this.it = it;
		this.join = join;
		sch.addAll(l.getSchema());
		sch.addAll(r.getSchema());
	}
	
	public Scanner open() {
		Scanner ls = l.open();
		TableScanner rs = (TableScanner) r.open();
		Index idx = it.open();
		return new IndexJoinScanner(ls, idx, join, rs);
	}

	public int blockAccessed() {
		return l.blockAccessed() + (l.outputSize() * it.blockAccessed()) + outputSize();
	}

	public int distinctSize(Attribute attr) {
		if (l.getSchema().hasAttribute(attr))
			return l.distinctSize(attr);
		else
			return r.distinctSize(attr);
	}

	public Schema getSchema() {
		return sch;
	}

	public int outputSize() {
		return l.outputSize() * it.outputSize();
	}
	
}
